package com.example.logisticsingle.authorization;


import com.example.logisticsingle.constants.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private FailureAuthenticationHandler failureAuthenticationHandler;
    @Autowired
    private SuccessAuthenticationHandler successAuthenticationHandler;
    @Autowired
    private RememberMeHandler rememberMeHandler;
    @Autowired
    private SSOLogoutSuccessHandler ssoLogoutSuccessHandler;
    /**
     * 注入身份管理器bean
     */
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 把userService 放入AuthenticationManagerBuilder里
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 用自己的登陆逻辑以及加密器
        auth.authenticationProvider(authenticationProvider());
        /*
         * auth.userDetailsService(userDetailsService).passwordEncoder(new
         * PasswordEncoder() {
         *
         * @Override public boolean matches(CharSequence rawPassword, String
         * encodedPassword) { return encodedPassword.equals(rawPassword.toString()); }
         *
         * @Override public String encode(CharSequence rawPassword) { return
         * rawPassword.toString(); } });
         */
        /**
         * 将密码加密
         */
        //auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置拦截忽略文件夹,可以对静态资源放行
        web.ignoring().antMatchers("/static/**","/css/**", "/js/**","/images/**")
                .and()
                .ignoring().antMatchers("/v2/api-docs",
                        "/swagger-resources/configuration/ui",
                        "/swagger-resources",
                        "/swagger-resources/configuration/security",
                        "/swagger-ui.html"
                );
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
        //return new MessageDigestPasswordEncoder("SHA-256");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.httpBasic()  //httpBasic 登录
        http.formLogin()
                .loginPage("/login")// 登陆的url
                .loginProcessingUrl("/authentication/form") // 自定义登录路径
                .failureHandler(failureAuthenticationHandler) // 自定义登录失败处理
                .successHandler(successAuthenticationHandler) // 自定义登录成功处理
                //.successForwardUrl("/")
                //.failureForwardUrl("/login")
                .and()
                .logout()
                .logoutUrl("/authentication/logout")
                .logoutSuccessHandler(ssoLogoutSuccessHandler)
                .and()
                .authorizeRequests()// 对请求授权
                .antMatchers("/login","/authentication/**","/authentication/require",
                        "/authentication/form").permitAll()
                // swagger start

                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers("/configuration/security").permitAll()
                // swagger end
                .anyRequest() // 任何请求
                .authenticated() // 都需要身份认证
                .and()
                .rememberMe().rememberMeParameter(Config.REMEMBERME_NAME)
                .rememberMeCookieName(Config.REMEMBERME_NAME)
                .tokenRepository(rememberMeHandler)
                .tokenValiditySeconds(AuthProperties.token.remembermeExpireTime)
                .userDetailsService(userDetailsService)
                .and()
                .csrf().disable()// 禁用跨站攻击
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //基于token，不需要session
        // http.addFilterBefore(tokenAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        http.headers().cacheControl();	//禁用缓存
        http.exceptionHandling().authenticationEntryPoint(new UnAuthorizedEntryPoint())
                .accessDeniedHandler(new AuthAccessDeineHandler());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        authenticationProvider.setHideUserNotFoundExceptions(false);
        return authenticationProvider;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationManager(authenticationManagerBean());
        loginFilter.setAuthenticationSuccessHandler(successAuthenticationHandler);
        loginFilter.setAuthenticationFailureHandler(failureAuthenticationHandler);
        return loginFilter;

    }
}
